package com.shujia.service;

import com.shujia.bean.Message;
import com.shujia.bean.User;
import com.shujia.dao.UserDao;
import com.shujia.util.MD5;

/**
 * @author yangjiming
 * @create 2021-03-30 21:28
 */
public class UserService {
    UserDao userDao = new UserDao();

    public Message login(String username, String password) {
        User user = userDao.findUserByUsername(username);

        if (user == null) {
           return new Message(300,"用户名不存在");
        }
        String md5Password = MD5.md5(password);
        if (!md5Password.equals(user.getPassword())) {
            return new Message(300,"密码错误");
        }
        return new Message(200,"登录成功");
    }

    public Message register(String username, String password, String newPassword) {
        User user = userDao.findUserByUsername(username);
        //判断用户名是否存在
        if(user!=null){
            return new Message(300,"用户名已存在");
        }
        //判断密码是否一致
        if(!password.equals(newPassword)){
            return new Message(300,"密码不一致");
        }
        //进行密码加密，存入数据库
        String md5Password = MD5.md5(password);
        int insert = userDao.insert(username, md5Password);
        if(insert==0){
            return new Message(300,"注册失败");
        }
        return new Message(200,"登录成功");
    }

    public Message modifyPassword(String username,String password,String newPassword,String nowPassword){
        User user = userDao.findUserByUsername(username);
        //判断用户名是否存在
        if(user==null){
            return new Message(300,"用户名不存在");
        }
        //判断原密码是否正确
        if(!MD5.md5(password).equals(user.getPassword())){
            return new Message(300,"密码错误");
        }
        if(!newPassword.equals(nowPassword)){
            return new Message(300,"密码不一致");
        }
        int i = userDao.upadtePasswordByUsername(username, MD5.md5(newPassword));
        if(i==0){
            return new Message(300,"修改失败");
        }
        return new Message(200,"修改成功");
    }
}
